<template>
  <div class="echarts-card" :id="elid">
    <vue-charts :style="style" :ref="LoadEchartRef" :option="option" @finished="onFinished"/>
  </div>
</template>

<script lang="ts">
import './echarts'
import VueCharts from 'vue-echarts'
import {use} from 'echarts/core'
import {CanvasRenderer} from 'echarts/renderers'
import {BarChart} from 'echarts/charts'
import {GridComponent, TooltipComponent, MarkLineComponent, LegendComponent} from 'echarts/components'

use([CanvasRenderer, BarChart, GridComponent, TooltipComponent, MarkLineComponent, LegendComponent])
import {PropType, defineComponent, computed, watch, nextTick, onMounted, ref} from "vue"
import {ChartType} from "@/components/DataEcharts/EchartsType";
import {ChartHandling} from "@/components/DataEcharts/DataHandling";
import {getRawData} from "@/units/tool";
import {CreateKey} from "@/units/system";

export default defineComponent({
  name: "DataEcharts",
  components: {VueCharts},
  props: {
    hideHeader: Boolean,
    data: {
      type: Object as PropType<ChartType>,
      required: true
    },
    shadow: {
      type: String as PropType<"always" | "never" | "hover">,
      default: 'hover'
    },
    height: {
      type: [String],
      default() {
        return '400px';
      }
    }
  },
  setup(props) {
    //是否初始化
    const init = ref<boolean>(false)

    //容器ID
    const elid: string = CreateKey()

    //容器宽度
    const width = ref<string>('100%')

    //图表实例
    const echart = ref<any>(null)
    /**
     * 统计图标配置
     */
    const option = computed(() => {
      return ChartHandling(props.data)
    })

    /**
     * 图表样式
     */
    const style = computed(() => {
      return {
        height: props.height,
        width: width
      }
    })

    /**
     * 监听数据变化,重载图表
     */
    watch(() => option, newValue => {
      echart?.value?.setOption(getRawData(newValue))
      resize()
    }, {
      deep: true
    })


    /**
     * 窗口变化重新初始化
     */
    function resize() {
      nextTick(() => {
        const ContainerWidth = document.getElementById(elid)?.offsetWidth;
        width.value = ContainerWidth ? (`${ContainerWidth}px`) : '100%'
        echart?.value?.resize();
      });
    }

    /**
     * 监控窗口事件
     */
    window.addEventListener('resize', resize)

    return {
      elid,
      style,
      option,
      LoadEchartRef: (ref: any) => echart.value = ref,

      onFinished() {
        if (init.value === false) {
          setTimeout(() => resize(), 200)
        }
        init.value = true
      }
    }
  }
})
</script>
<style lang="scss" scoped>
.echarts-card {
  padding: 0;
}
</style>